package com.zj.executor;

import com.zj.mapping.MappedStatement;
import com.zj.sqlSession.ResultHandler;
import com.zj.statement.PreparedStatementHandler;
import com.zj.statement.StatementHandler;
import com.zj.transaction.Transaction;
import com.zj.utils.Configuration;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class SimpleExecutor extends BaseExecutor {

    public SimpleExecutor(Configuration configuration, Transaction transaction) {
        super(configuration, transaction);
    }

    public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
        Statement stmt = null;
        try {
            Configuration configuration = ms.getConfiguration();
            StatementHandler handler = new PreparedStatementHandler(this, ms, parameter);
            Connection connection = transaction.getConnection();
            stmt = handler.prepare(connection);
            handler.parameterize(stmt);
            return handler.update(stmt);
        } finally {
            closeStatement(stmt);
        }
    }
    protected void closeStatement(Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            //ignore
        }
    }


    public <E> List<E> doQuery(MappedStatement ms, Object parameter) throws SQLException {
        Statement stmt = null;
        try {
            Configuration configuration = ms.getConfiguration();
            StatementHandler handler = new PreparedStatementHandler(this, ms, parameter);

            Connection connection = transaction.getConnection();
            stmt = handler.prepare(connection);
            handler.parameterize(stmt);
            return handler.<E>query(stmt);
        } finally {
            closeStatement(stmt);
        }
    }
}
